using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace LP2
{

    public class Game : Microsoft.Xna.Framework.Game
    {
        Background bg;
        Physic Phy;
        Shooter shooter;
        List<Item> listItems;
        CreaturesList creatureList;
        CreaturePropertyConfig creaturePropConfig;
        ReadXML xmlReader;

        //Lista que almacenara los enemigos que estan bajo efectos de alguna fuerza (rebote,colision,etc)
        List<Enemy> EnemysWithF;

        public GraphicsDeviceManager graphics; //Maneja los graficos
        SpriteBatch SpBatch;

        Boolean Click;
        Boolean ShootFlag;
        Boolean StoppedBidFlag;
        Boolean FlagExit = false;
        private bool paused = false;
        private bool pauseKeyDown = false;
        float t = 0f;
        int turnAlly = 0;

        MouseState m;
        MouseState mshoot;
        int level;



        public Game(int nivelSelected)
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            //Configuracion de ventana principal del juego **********************************

            this.IsMouseVisible = true;
            //this.graphics.IsFullScreen = true;
            Window.Title = "Juego LP2";
            //*******************************************************************************
            this.level = nivelSelected;

        }

        protected override void Initialize()
        {
            bg = new Background();
            shooter = new Shooter();
            xmlReader = new ReadXML();
            //xmlReader.ReadXMLLevel();
            xmlReader.level = this.level;
            EnemysWithF = new List<Enemy>();

            creaturePropConfig = new CreaturePropertyConfig();
            creatureList = new CreaturesList(shooter, creaturePropConfig);

            xmlReader.ReadXMLBackground(bg);
            xmlReader.ReadXMLInitConfigCreatures(creaturePropConfig);
            xmlReader.ReadXMLCreatures(creatureList);



            Phy = new Physic();
            SpBatch = new SpriteBatch(GraphicsDevice);

            listItems = new List<Item>();
            listItems.Add(new Item("Big Bird"));
            listItems.Add(new Item("Mini bird comprimido"));
            listItems.Add(new Item("Speed plus"));

            Click = false;
            ShootFlag = false;
            StoppedBidFlag = false;

            base.Initialize();
        }

        protected override void LoadContent()
        {
            creatureList.LoadContent(Content); //Este metodo carga los graficos de las clases
            bg.LoadContent(Content);
        }

        protected override void UnloadContent()
        {

        }


        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            Boolean clickAlly;
            Boolean colisionBG;
            Boolean colisionEnemy;
            
            checkPauseKey(Keyboard.GetState());

            if (!paused)
            {
                if ((creatureList.getListAllys().Count() == 0) || (creatureList.getListEnemys().Count() == 0))
                {
                    if (StoppedBidFlag && (creatureList.getListEnemys().Count() == 0))
                    {
                        this.Exit();
                        FlagExit = true;
                        xmlReader.releaseLevel(level);

                    }

                    if (creatureList.getListAllys().Count() == 0)
                    {
                        this.Exit();
                        FlagExit = true;
                    }
                }

                if (!FlagExit)
                {

                    Ally allyCurrent = creatureList.getListAllys()[turnAlly];
                    if ((clickAlly = allyCurrent.ClickOnMe(m = Mouse.GetState())) || Click)
                    {
                        //se mueve el bird dependiendo de la direccion del mouse
                        allyCurrent.MoveWithClick(m, shooter);

                        if (clickAlly)
                        {
                            mshoot = m;
                        }

                        Click = true;

                        if (ButtonState.Pressed != Mouse.GetState().LeftButton)
                        {
                            Click = false;
                            ShootFlag = true;
                            StoppedBidFlag = false;
                        }
                    }
                    else
                    {
                        //una vez soltado, se dispara al bird
                        if (ShootFlag)
                        {
                            if (allyCurrent.StopBird(this) && !StoppedBidFlag)
                            {
                                Boolean res = true;
                                foreach (Enemy e in EnemysWithF)
                                {
                                    if (!e.getflagStopped()) res = false;
                                }

                                if (res)
                                {
                                    Click = false;
                                    t = 0;
                                    if (EnemysWithF.Count() == 0)
                                        ShootFlag = false;

                                    StoppedBidFlag = true;
                                    t = 0f;
                                    creatureList.RemoveAlly(turnAlly);
                                    //enemy.setAttacked(false);
                                }
                            }
                            else
                            {
                                colisionBG = Phy.ColisionBackground(allyCurrent, bg.getObstacles(), shooter);
                                colisionEnemy = false;

                                foreach (Enemy e in creatureList.getListEnemys())
                                {
                                    if (Phy.ColisionCreatures(allyCurrent, e, shooter))
                                    {
                                        EnemysWithF.Add(e);
                                        colisionEnemy = true;
                                    }
                                }

                                if (colisionBG || colisionEnemy)
                                {
                                    //Console.WriteLine("Han colisionado!!!");
                                    creatureList.getListAllys()[turnAlly].incNumberColision();
                                    t = 0f;
                                }
                                else
                                {
                                    allyCurrent.setNumberColision(0);
                                }

                                allyCurrent.ShotBird(mshoot, t, shooter, this.Phy);
                                allyCurrent.setFlagColisionEnemyDestroy(false);
                                t += 0.05f;
                            }


                            //Para la logica de los enemys

                            List<Enemy> EnemysWithFAux = new List<Enemy>(EnemysWithF);

                            foreach (Enemy e in EnemysWithF)
                            {
                                //Console.WriteLine(e.getPosition());
                                //Console.WriteLine(bg.getObstacles()[1]);

                                if (e.IsDie())
                                {
                                    Console.WriteLine("Creature Die");
                                    allyCurrent.setFlagColisionEnemyDestroy(true);
                                    //Si no muere, entonces el aliado debe seguir su trayectoria
                                    shooter.setV0X(-shooter.getV0X());
                                    creatureList.RemoveEnemy(e);
                                    EnemysWithFAux.Remove(e);
                                }
                                else
                                {
                                    Boolean ColBG = true;

                                    if (e.getFAplicada() >= 1)
                                    {
                                        e.MoveCuzColision(allyCurrent, Phy);
                                        ColBG = Phy.ColisionBackground(e, bg.getObstacles(), shooter);

                                        if (ColBG)
                                        {
                                            e.setFAplicada(Convert.ToSingle(e.getFAplicada() * 0.90 - 5));
                                            e.incNumberColision();
                                        }
                                        else
                                        {
                                            e.setNumberColision(0);
                                        }
                                    }
                                    else
                                    {
                                        EnemysWithFAux.Remove(e);
                                        e.setFlagStopped(true);
                                    }
                                }
                            }

                            if (EnemysWithFAux.Count() == 0)
                            {
                                EnemysWithF = EnemysWithFAux;
                                //ShootFlag = false;
                                //t = 0f;
                            }
                        }
                    }
                }
            }

            base.Update(gameTime);
        }


        protected override void Draw(GameTime gameTime)
        {
            if (paused)
            {
                GraphicsDevice.Clear(Color.Black);
                base.Draw(gameTime);
            }
            else
            {
                GraphicsDevice.Clear(Color.CornflowerBlue);
                base.Draw(gameTime);
            }
            bg.Draw(SpBatch);
            SpBatch.End();

            creatureList.Draw(SpBatch);
            SpBatch.End();


            //bg.Draw(SpBatch);
            //SpBatch.End();

        }

        private void checkPauseKey(KeyboardState keyboardState)
        {
            bool pauseKeyDownThisFrame = (keyboardState.IsKeyDown(Keys.P));
                
            // If key was not down before, but is down now, we toggle the
            // pause setting
            if (!pauseKeyDown && pauseKeyDownThisFrame)
            {
                if (!paused)
                    BeginPause(true);
                else
                    EndPause();
            }
            pauseKeyDown = pauseKeyDownThisFrame;
        }

        private void BeginPause(bool UserInitiated)
        {
            paused = true;
        }

        private void EndPause()
        {
            paused = false;
        }
    }
}


